package com.cuitrip.business.order;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.PorterDuff;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.cuitrip.apiservice.OrderBusiness;
import com.cuitrip.apiservice.ServiceBusiness;
import com.cuitrip.apiservice.model.ApiManager;
import com.cuitrip.app.MainApplication;
import com.cuitrip.app.base.CtException;
import com.cuitrip.app.base.CtFetchCallback;
import com.cuitrip.app.rong.RongCloudEvent;
import com.cuitrip.business.date.model.ServiceDateDetail;
import com.cuitrip.business.date.ui.MonthSelectDateAdapter;
import com.cuitrip.business.home.IndexActivity;
import com.cuitrip.business.login.LoginInstance;
import com.cuitrip.business.order.detail.OrderFormActivity;
import com.cuitrip.business.order.model.OrderItem;
import com.cuitrip.business.order.model.PersonSelectModel;
import com.cuitrip.business.order.ui.PersonNumberHolderView;
import com.cuitrip.business.tripservice.model.ServiceDetail;
import com.cuitrip.business.tripservice.model.ServiceInfo;
import com.cuitrip.business.user.model.CtUserInfo;
import com.cuitrip.component.item.CtTextView;
import com.cuitrip.component.statelayout.StateLayout;
import com.cuitrip.im.CtInfoNotificationMsgItemProvider;
import com.cuitrip.im.model.CTInformationNotificationMessage;
import com.cuitrip.im.proxy.CtRongInfoProxy;
import com.cuitrip.service.R;
import com.cuitrip.util.I118Util;
import com.cuitrip.util.ResourceUtil;
import com.cuitrip.util.text.TextProxy;
import com.cuitrip.util.time.InputTime;
import com.cuitrip.util.time.OutputTime;
import com.cuitrip.util.time.TimeUtil;
import com.cuitrip.util.track.TrackUtil;
import com.facebook.appevents.AppEventsConstants;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
import com.google.android.gms.analytics.ecommerce.Product;
import com.google.android.gms.analytics.ecommerce.ProductAction;
import com.lab.adapter.BaseHolderView;
import com.lab.adapter.BasePageAdapter;
import com.lab.adapter.HolderViewAdapter;
import com.lab.app.customui.CustomUiConfig;
import com.lab.app.customui.CustomUiFragmentActivity;
import com.lab.component.list.LinearListView;
import com.lab.jumper.Jumper;
import com.lab.logtrack.AppLog;
import com.lab.network.config.CtResponseCode;
import com.lab.network.model.CtApiResponse;
import com.lab.network.model.IProxyCallback;
import com.lab.network.model.ProxyResult;
import com.lab.network.proxy.ApiProxy;
import com.lab.utils.LogHelper;
import com.lab.utils.MessageUtils;
import com.lab.utils.ToastUtil;
import com.lab.widget.CtGridView;
import com.lab.widget.WordCountView;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.TimeZone;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * 下单页面
 * Created on 7/18.
 */
public class OrderCreateActivity extends CustomUiFragmentActivity implements IProxyCallback {

    public static final String SERVICE_INFO = "ORDER_SERVICE_INFO";
    public static final String SERVICE_ID_KEY = "service_id";
    public static final String ORDER_KEY = "OrderCreateActivity.ORDER_KEY";
    public static final String EDIT_KEY = "OrderCreateActivity.EDIT_KEY";
    @Bind(R.id.person_limit)
    CtTextView personLimit;

    private OrderItem mOrder;


    public static final int ORDER_DATE_LIMIT = 60;

    @Bind(R.id.time_zone_text)
    CtTextView timeZoneText;
    @Bind(R.id.month_title)
    TextView monthTitle;
    @Bind(R.id.state_layout)
    StateLayout stateLayout;
    @Bind(R.id.date_view_pager)
    ViewPager dateViewPager;
    @Bind(R.id.person_num_selector)
    LinearListView personNumSelector;
    @Bind(R.id.prev_action)
    ImageView prevAction;
    @Bind(R.id.next_action)
    ImageView nextAction;
    @Bind(R.id.messageView)
    WordCountView messageView;
    @Bind(R.id.submit_order)
    TextView submitOrder;
    @Bind(R.id.preference_view)
    LinearLayout preferenceView;

    private ServiceInfo mService;
    private String serviceId;

    private boolean isEdit = false;

    private ArrayList<Calendar> calendarList = new ArrayList<>();
    private ArrayList<PersonSelectModel> personNumberList = new ArrayList<>();
    private List<Long> mAvailableDateList = new ArrayList<Long>();
    private List<Long> mBookedDateList = new ArrayList<Long>();

    protected long selectTime = -1L;//已选择的时间
    private int personNum = 0;
    private TimeZone serviceTimeZone;

    private Animation mShakeAnimation;


    private ApiProxy mApiProxy = new ApiProxy(this);

    public static void start(Context context, ServiceInfo serviceInfo) {
        if (null == serviceInfo) {
            return;
        }
        Intent intent = new Intent(context, OrderCreateActivity.class)
                .putExtra(SERVICE_INFO, serviceInfo);
        Jumper.launchActivity(context, intent);
    }

    public static void start(Context context, String sid) {
        if (TextUtils.isEmpty(sid)) {
            return;
        }
        Intent intent = new Intent(context, OrderCreateActivity.class)
                .putExtra(SERVICE_ID_KEY, sid);
        Jumper.launchActivity(context, intent);
    }

    public static void startModify(Activity activity, OrderItem orderItem) {
        if (null == orderItem) {
            return;
        }
        Intent intent = new Intent(activity, OrderCreateActivity.class)
                .putExtra(ORDER_KEY, orderItem).putExtra(EDIT_KEY, true);
        Jumper.launchActivity(activity, intent);
    }


    protected void onCreate(Bundle savedInstanceState) {
        Intent intent = getIntent();
        isEdit = intent.getBooleanExtra(EDIT_KEY, false);
        if (intent.hasExtra(ORDER_KEY)) {
            mOrder = (OrderItem) intent.getSerializableExtra(ORDER_KEY);
            serviceId = mOrder.getSid();
            try {
                selectTime = Long.parseLong(mOrder.getServiceDate());
                personNum = Integer.parseInt(mOrder.getBuyerNum());
            } catch (Exception e) {

            }
        } else if (intent.hasExtra(SERVICE_ID_KEY)) {
            serviceId = intent.getStringExtra(SERVICE_ID_KEY);
        } else {
            mService = (ServiceInfo) intent.getSerializableExtra(SERVICE_INFO);
            serviceId = mService.getSid();
        }
        TrackUtil.trackScreenName("/booking/submit");
        super.onCreate(savedInstanceState, R.layout.ct_create_order);
    }

    @Override
    public void initView() {
        ButterKnife.bind(this);
        prevAction.setColorFilter(ResourceUtil.getColor(R.color.ct_black), PorterDuff.Mode.SRC_ATOP);
        nextAction.setColorFilter(ResourceUtil.getColor(R.color.ct_black), PorterDuff.Mode.SRC_ATOP);
        mShakeAnimation = AnimationUtils.loadAnimation(this, R.anim.shake);


        preferenceView.setVisibility(isEdit ? View.GONE : View.VISIBLE);
        messageView.setHint(getString(R.string.book_submit_additional_desc));
    }

    private void renderPersonSelectorView() {
        final HolderViewAdapter personSelectorAdapter = new HolderViewAdapter(this, personNumberList, PersonNumberHolderView.class);
        personSelectorAdapter.setHolderViewCallback(new HolderViewAdapter.HolderViewCallback() {
            @Override
            public void onHolderViewInvalidate(BaseHolderView holderView, int position) {
                if (holderView instanceof PersonNumberHolderView) {
                    PersonNumberHolderView personNumberHolderView = (PersonNumberHolderView) holderView;
                    personNumberHolderView.setOnSelectCallback(new OnSelectCallback() {
                        @Override
                        public void onSelect(int position) {
                            personNum = personNumberList.get(position).getPersonNum();
                            for (PersonSelectModel personSelectModel : personNumberList) {
                                if (personSelectModel.getPersonNum() == personNum) {
                                    personSelectModel.setSelected(true);
                                } else {
                                    personSelectModel.setSelected(false);
                                }
                            }
                            personSelectorAdapter.notifyDataSetChanged();
                        }
                    });
                }
            }
        });
        personNumSelector.setAdapter(personSelectorAdapter);
    }

    private void inflatePersonNumber(int min, int max, int defaultSelect) {
        for (int i = 1; i <= 6; i++) {
            boolean isEnabled = true;
            PersonSelectModel personSelectModel = new PersonSelectModel(i, isEnabled, false);
            if (defaultSelect == i) {
                personSelectModel.setSelected(true);
            }
            if (min <= i && i <= max) {
                personNumberList.add(personSelectModel);
            }
        }
    }

    @Override
    public void initListener() {
        stateLayout.setOnClickStateLayoutListener(new StateLayout.OnClickStateLayoutListener() {
            @Override
            public void onClick(StateLayout.State state) {
                initData();
            }
        });
        dateViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                updateTopCalendarBar(calendarList.get(position));

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    public void initData() {
        if (mService != null) {
            bindData();
        } else {
            stateLayout.changeState(StateLayout.State.Loading);
            ServiceBusiness.getServiceDetail(mApiProxy, serviceId, 0);
        }

    }

    private void bindData() {
        serviceTimeZone = TimeZone.getTimeZone(mService.getTimeZone());
        if (personNum == 0) {
            personNum = mService.getMinBuyerNum();
        }
        inflatePersonNumber(mService.getMinBuyerNum(), mService.getMaxbuyerNum(), personNum);
        personLimit.setText(TextProxy.getInstance().formatWithSingleAndMore(mService.getMaxbuyerNum(), R.string.book_submit_people_max_one, R.string.book_submit_people_max_more));
        renderPersonSelectorView();

        bindTimeZone(TimeZone.getTimeZone(mService.getTimeZone()));
        requestDate(serviceId);
        messageView.setHint(getString(R.string.book_message_additional));
    }


    private void bindTimeZone(TimeZone timeZone) {
        int offset = timeZone.getRawOffset() / (1000 * 60 * 60);
        timeZoneText.setText(getString(R.string.time_zone_local) + ":" +
                TimeUtil.formatTime(
                        InputTime.build(System.currentTimeMillis()),
                        OutputTime.getInstance(OutputTime.OutputType.Type_Minute, timeZone)
                ) + " (UTC " + (offset >= 0 ? ("+" + offset) : offset) + ")");
    }


    private void updateBookDate() {
        inflateDate();
        mAdaper.setData(calendarList);
        dateViewPager.setAdapter(mAdaper);
        dateViewPager.setOffscreenPageLimit(1);
        updateTopCalendarBar(calendarList.get(dateViewPager.getCurrentItem()));
    }


    private void requestDate(String sid) {
        stateLayout.changeState(StateLayout.State.Loading);
        ServiceBusiness.getServiceAvailableAndBookedDate(mApiProxy, sid);
    }

    private void updateMonthView(Calendar calendar) {
        String formatMonth = TimeUtil.formatTime(InputTime.build(calendar.getTime().getTime(), serviceTimeZone),
                OutputTime.getInstance(OutputTime.OutputType.TYPE_MONTH, serviceTimeZone));

        monthTitle.setText(formatMonth);
    }

    private ArrayList<Calendar> inflateDate() {
        Calendar serviceZoneCalendar = Calendar.getInstance(serviceTimeZone);
        long zeroZonetimeMills = InputTime.outputOtherZoneTimeMills(serviceZoneCalendar.getTimeInMillis(), serviceTimeZone, TimeUtil.getZeroZone());

        Calendar todayCalendar = Calendar.getInstance(TimeUtil.getZeroZone());

        todayCalendar.setTimeInMillis(zeroZonetimeMills);
        todayCalendar.set(Calendar.HOUR_OF_DAY, 0);
        todayCalendar.set(Calendar.MINUTE, 0);
        todayCalendar.set(Calendar.SECOND, 0);
        todayCalendar.set(Calendar.MILLISECOND, 0);

        Calendar maxCalendar = Calendar.getInstance(TimeUtil.getZeroZone());
        maxCalendar.setTimeInMillis(zeroZonetimeMills);
        maxCalendar.set(Calendar.HOUR_OF_DAY, 23);
        maxCalendar.set(Calendar.MINUTE, 59);
        maxCalendar.set(Calendar.SECOND, 59);
        maxCalendar.set(Calendar.MILLISECOND, 999);
        maxCalendar.add(Calendar.DAY_OF_YEAR, ORDER_DATE_LIMIT - 1);
        int showMonthCount = (maxCalendar.get(Calendar.YEAR) - todayCalendar.get(Calendar.YEAR)) * 12 + (maxCalendar.get(Calendar.MONTH) - todayCalendar.get(Calendar.MONTH));

        for (int i = 0; i <= showMonthCount; i++) {
            Calendar calendar = Calendar.getInstance(TimeUtil.getZeroZone());
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);
            calendar.add(Calendar.MONTH, i);
            calendarList.add(calendar);
        }
        return calendarList;
    }

    protected void onLoginSuccess() {
        createOrder();
    }

    protected void onLoginFailed() {
    }

    private void createOrder() {
        if (selectTime == -1L) {
            dateViewPager.startAnimation(mShakeAnimation);
            return;
        }
        showNoCancelDialog();
        LogHelper.e("omg", "create order" + mService.getInsiderId() + "|" + mService.getSid() + "|" + mService.getName() + "|" +
                personNum + "|" + mService.getPrice() + "|" + mService.getMoneyType());

        OrderBusiness.createOrder(mApiProxy, mService.getInsiderId(), mService.getSid(), mService.getName(),
                selectTime,
                String.valueOf(personNum), mService.getPrice(), mService.getMoneyType(), mService.getShowCurrency());

    }

    private void modifyOrder() {
        if (selectTime == -1L) {
            dateViewPager.startAnimation(mShakeAnimation);
            return;
        }
        showNoCancelDialog();
        OrderBusiness.modifyOrder(mApiProxy, mOrder.getOid(), mOrder.getSid(), mService.getName(),
                selectTime, String.valueOf(personNum), mService.getPrice(), mService.getMoneyType());
    }


    @Override
    public boolean initCloseTopBar() {
        return false;
    }

    @Override
    public void onTopbarLeftPress() {
        finish();
    }

    @Override
    public CustomUiConfig initCustomUiConfig() {
        CustomUiConfig config = new CustomUiConfig();
        config.mTopbarMiddleAreaName = getString(R.string.main_nav_book);
        config.mTopbarLeftAreaName = getString(R.string.back_icon);
        return config;
    }


    BasePageAdapter mAdaper = new BasePageAdapter<Calendar>() {

        private final ArrayDeque<CtGridView> currentViews = new ArrayDeque<>();

        private void updateSelectTime(long time) {
            selectTime = time;
            notifySelected();
        }

        private void notifySelected() {
            for (CtGridView gridView : currentViews) {
                MonthSelectDateAdapter monthSelectAdapter = (MonthSelectDateAdapter) gridView.getAdapter();
                monthSelectAdapter.setSelectDate(selectTime);
                monthSelectAdapter.notifyDataSetChanged();
            }
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        public Object instantiateItem(ViewGroup container, int position) {
            CtGridView view = (CtGridView) View.inflate(OrderCreateActivity.this, R.layout.ct_grid_date, null);
            MonthSelectDateAdapter monthDateAdapter = new MonthSelectDateAdapter(OrderCreateActivity.this);
            monthDateAdapter.setAvailableDateList(mAvailableDateList);
            monthDateAdapter.setBookDateList(mBookedDateList);
            monthDateAdapter.setSelectDate(selectTime);
            view.setAdapter(monthDateAdapter);
            monthDateAdapter.setCalendar(mData.get(position));
            monthDateAdapter.setOnSelectChangeCallBack(new MonthSelectDateAdapter.OnSelectChangeCallBack() {

                @Override
                public void onSelect(Long time) {
                    updateSelectTime(time);
                }

            });
            container.addView(view);
            currentViews.add(view);
            return view;
        }

        public void destroyItem(ViewGroup container, int position, Object object) {
            if (object instanceof CtGridView) {
                CtGridView pagerView = (CtGridView) object;
                currentViews.remove(pagerView);
            }
            container.removeView((View) object);
        }
    };

    @Override
    public boolean onProxyResult(ProxyResult<?> result) {
        CtApiResponse response = (CtApiResponse) result.getData();
        if (response.getApiName().equals(ApiManager.GET_AVAILABLE_BOOK)) {
            if (response != null && response.code == CtResponseCode.RESULT_OK) {
                stateLayout.changeState(StateLayout.State.INIT);
                if (response.result instanceof ServiceDateDetail) {
                    ServiceDateDetail data = (ServiceDateDetail) response.result;
                    stateLayout.changeState(StateLayout.State.INIT);
                    List<Long> availableDateList = data.getAvailableDate();
                    List<Long> bookedDateList = data.getBookedDate();
                    mAvailableDateList.clear();
                    mBookedDateList.clear();
                    if (availableDateList != null) {
                        mAvailableDateList.addAll(availableDateList);
                    }
                    if (bookedDateList != null) {
                        mBookedDateList.addAll(bookedDateList);
                    }
                }
            } else {
                MessageUtils.showToast(response.msg);
            }
            updateBookDate();
        } else if (ApiManager.CREATE_ORDER.equals(response.getApiName())) {
            hideNoCancelDialog();
            if (response.isResponseNormal()) {
                if (response.result instanceof OrderItem) {
                    final OrderItem item = (OrderItem) response.result;
                    item.setServicePIC(mService.getBackPic());
                    sendBroadcast(
                            new Intent(OrderItem.ORDER_STATUS_CHANGED_ACTION));
                    trackOrderCreate(item);

                    try {
                        String myid = "";
                        CtUserInfo userInfo = LoginInstance.getInstance().getUserInfo();
                        if (userInfo != null) {
                            myid = userInfo.getUid();
                        }
                        List<String> userIds = new ArrayList<>();
                        userIds.add(mService.getInsiderId());
                        userIds.add(myid);
                        String title = item.getOid();
                        RongCloudEvent.getInstance().startConversation(title, userIds, item.getOid(), new CtFetchCallback<String>() {
                            @Override
                            public void onSuc(String s) {
                                AppLog.d("OrderCreateActivity", "GET TARGET ID " + s);
                                process2OrderPage(item);
                            }

                            @Override
                            public void onFailed(CtException throwable) {
                                process2OrderPage(item);
                                AppLog.d("OrderCreateActivity", "GET CtException " + throwable.getMessage());
                            }
                        });
                    } catch (Exception e) {
                        MessageUtils.showToast(R.string.feedback_no_internet_1);
                    }
                }
            } else {
                if (!TextUtils.isEmpty(response.msg)) {
                    MessageUtils.showToast(response.msg);
                }
            }

        } else if (ApiManager.GET_SERVICE_DETAIL.equals(response.getApiName())) {
            if (response.isResponseNormal()) {
                if (response.result instanceof ServiceDetail) {
                    ServiceDetail serviceDetail = (ServiceDetail) response.result;
                    mService = serviceDetail.getServiceInfo();
                    stateLayout.changeState(StateLayout.State.INIT);
                    bindData();
                }
            } else {
                stateLayout.changeState(StateLayout.State.NoNetwork);
                if (!TextUtils.isEmpty(response.msg)) {
                    MessageUtils.showToast(response.msg);
                }
            }

        } else if (ApiManager.MODIFY_ORDER.equals(response.getApiName())) {
            hideNoCancelDialog();
            if (response.isResponseNormal()) {
                sendBroadcast(
                        new Intent(OrderItem.ORDER_STATUS_CHANGED_ACTION));
                InputTime zeroDateZone = InputTime.build(selectTime, TimeUtil.getZeroZone());
                String commonFormatTime = TimeUtil.formatTime(zeroDateZone, OutputTime.getInstance(OutputTime.OutputType.TYPE_COMMON_ENGLISH, TimeUtil.getZeroZone()));

                String nickName = LoginInstance.getInstance().getUserInfo().getNick();
                CTInformationNotificationMessage message = CtRongInfoProxy.getInstance().
                        getModifyOrderMessage(nickName, personNum, zeroDateZone.getTime(), commonFormatTime);
                CtRongInfoProxy.getInstance().sendSystemMessage(mOrder.getTargetId(), message, null);

                ToastUtil.toast(R.string.feedback_edit_suc);

                finish();
            } else {
                MessageUtils.showToast(response.msg);
            }


        }
        return false;
    }

    private void trackOrderCreate(OrderItem item) {
        /**
         * facebook 统计数据
         */
        Bundle parameters = new Bundle();
        parameters.putString(AppEventsConstants.EVENT_PARAM_CURRENCY, item.getPayCurrency());
        parameters.putString(AppEventsConstants.EVENT_PARAM_CONTENT_ID, item.getOid());
        Double doubleValue = 0.0;
        try {
            doubleValue = Double.parseDouble(item.getServicePrice());
        } catch (Exception e) {

        }
        MainApplication.getInstance().logger.logEvent(AppEventsConstants.EVENT_NAME_INITIATED_CHECKOUT, doubleValue, parameters);
        /**
         * ======end
         */

        try {
            Product product = new Product()
                    .setId(mService.getSid())
                    .setName(mService.getName())
                    .setCategory(mService.toCateString())
                    .setQuantity(Integer.valueOf(item.getBuyerNum()))
                    .setBrand(I118Util.getLanguageTag())
                    .setPrice(Double.parseDouble(mService.getPrice()));
            ProductAction productAction = new ProductAction(ProductAction.ACTION_PURCHASE)
                    .setTransactionId(item.getOid())
                    .setTransactionRevenue(doubleValue);
            HitBuilders.ScreenViewBuilder builder = new HitBuilders.ScreenViewBuilder()
                    .addProduct(product)
                    .setProductAction(productAction);

            Tracker t = MainApplication.getInstance().getDefaultTracker();
            t.setScreenName("transaction");
            t.set("&cu", item.getPayCurrency());
            t.send(builder.build());
        } catch (Exception e) {

        }
    }

    private void process2OrderPage(OrderItem item) {
        hideNoCancelDialog();
        String nickName = LoginInstance.getInstance().getUserInfo().getNick();
        String formatDate = TimeUtil.formatTime(InputTime.build(selectTime, TimeUtil.getZeroZone()),
                OutputTime.getInstance(OutputTime.OutputType.TYPE_COMMON_ENGLISH, TimeUtil.getZeroZone()));

        CTInformationNotificationMessage message = CtRongInfoProxy.getInstance().getCommonOrderChangeMessage(CtInfoNotificationMsgItemProvider.CtParamKey.BOOK_MSG_BOOKED,
                nickName, selectTime, formatDate);
        String travellerNotes = messageView.getContent();
        IndexActivity.gotoTab(OrderCreateActivity.this, IndexActivity.ORDER_TAB_INDEX);
        OrderFormActivity.start(OrderCreateActivity.this, item.getOid(), message, travellerNotes);
        finish();
    }

    @OnClick({R.id.prev_action, R.id.next_action, R.id.submit_order})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.prev_action:
                dateViewPager.setCurrentItem(dateViewPager.getCurrentItem() - 1, true);
                break;
            case R.id.next_action:
                dateViewPager.setCurrentItem(dateViewPager.getCurrentItem() + 1, true);
                break;
            case R.id.submit_order:
                if (isEdit) {
                    modifyOrder();
                } else {
                    createOrder();
                }
                break;
        }
    }

    private void updateTopCalendarBar(Calendar calendar) {
        updateMonthView(calendar);
        prevAction.setVisibility(canGoBack() ? View.VISIBLE : View.INVISIBLE);
        nextAction.setVisibility(canGoForward() ? View.VISIBLE : View.INVISIBLE);
    }

    private boolean canGoForward() {
        return dateViewPager.getCurrentItem() < (mAdaper.getCount() - 1);
    }

    private boolean canGoBack() {
        return dateViewPager.getCurrentItem() > 0;
    }

    public interface OnSelectCallback {

        public void onSelect(int position);

    }

}
